﻿var manage = {
    //未选操作行提示
    nullRowMsg: "请单击选择行再操作功能",
    //写入等待
    showMask: function (obj) {
        obj = obj || $("body").eq(0);
        var mask = $("<div class=\"datagrid-mask\" />").css({
            display: "block", zIndex: 88888
        }).appendTo(obj);
        var msg = $("<div class=\"datagrid-mask-msg\" />");
        msg.css({
            display: "block", zIndex: 88888,
            backgroundPosition: "center",
            paddingRight: "6px",
            left: "50%", marginLeft: "-20px"
        }).appendTo(obj);
    },
    //移除等待
    hideMask: function (obj) {
        obj = obj || $("body").eq(0);
        obj.children("div.datagrid-mask").remove();
        obj.children("div.datagrid-mask-msg").remove();
    },
    //提示信息
    msg: function (content, fn) {
        $.messager.alert("提示", content, "info", fn);
    },
    //浮出信息
    slide: function (content) {
        $.messager.show({
            title: "提示", msg: content,
            height: "auto",
            showType: "null",
            style: { right: "", top: 5 }
        });
    },
    //确认提示
    confirm: function (content, handler) {
        $.messager.confirm("提示", content, handler);
    },
    //输入确认
    prompt: function (content, handler, value) {
        var prompt = $.messager.prompt("提示", content, handler);
        if (value) { $(".messager-input", prompt).val(value); }
    },
    //获取图标
    icon: function (value) {
        return $("<span class='list-span'/>").addClass(value).prop("outerHTML");
    },
    //获取图标
    iconText: function (value, text) {
        var span = $("<span class='l-btn-text l-btn-icon-left' />").addClass(value).html(text);
        var spanbox = $("<span class='l-btn-left' />").append(span);
        return $("<a class='list-link' href='javascript:void(0)' />").append(spanbox).prop("outerHTML");
    },
    //获取是否
    iconYesOrNo: function (value) {
        if ($.type(value) != "boolean") {
            return "";
        }
        if (value) {
            return manage.icon("icon-bullet_tick");
        }
        return manage.icon("icon-bullet_minus");
    },
    //获取按钮
    textButton: function (text, mtag, func, data) {
        var a = $("<a href='javascript:;' />").addClass(mtag + "func");
        a.css({ "color": "#4395ff", "text-decoration": "underline" });
        for (var key of Object.keys(data)) { a.attr("data-" + key, data[key]); }
        return a.attr("data-func", func).html(text).prop("outerHTML");
    },
    //获取按钮
    iconButton: function (value, text, mtag, func, data) {
        var span = $("<span class='l-btn-text l-btn-icon-left' />").addClass(value).html(text);
        var spanbox = $("<span class='l-btn-left' />").append(span);
        var a = $("<a class='list-link' href='javascript:;' />").addClass(mtag + "func");
        for (var key of Object.keys(data)) { a.attr("data-" + key, data[key]); }
        return a.append(spanbox).attr("data-func", func).prop("outerHTML");
    },
    //获取按钮
    iconUrlButton: function (value, text, url) {
        var span = $("<span class='l-btn-text l-btn-icon-left' />").addClass(value).html(text);
        var spanbox = $("<span class='l-btn-left' />").append(span);
        return $("<a class='list-link' target='_blank' />").append(spanbox).attr("href", url).prop("outerHTML");
    },
    //获取按钮
    iconNoTextButton: function (value, text, mtag, func, data) {
        var span = $("<span class='l-btn-text l-btn-icon-left' />").addClass(value);
        var spanbox = $("<span class='l-btn-left' />").append(span);
        var a = $("<a class='list-link' href='javascript:;' />").addClass(mtag + "func");
        for (var key of Object.keys(data)) { a.attr("data-" + key, data[key]); }
        return a.append(spanbox).attr("title", text).attr("data-func", func).prop("outerHTML");
    },
    //弹出窗口
    dialog: function (options) {
        options = manage.dialogInit(options);
        var div = $("<div />");
        if (options.id) { div.attr("id", options.id); }
        if (options.classes) { div.addClass(options.classes); }
        var dialog = div.dialog({
            bodyCls: options.bodyCls,
            iconCls: options.iconCls,
            title: options.title,
            width: options.width,
            height: options.height,
            href: options.href,
            content: options.content,
            modal: options.modal,
            cache: false,
            closable: options.closable,
            toolbar: options.toolbar,
            buttons: options.buttons,
            onLoad: function () {
                options.onLoad();
                manage.adjustmentDialog(dialog);
            },
            onClose: function () {
                options.onClose();
                $(this).dialog("destroy");
            }
        });
        manage.adjustmentDialog(dialog);
        return dialog;
    },
    //窗口初始化
    dialogInit: function (options) {
        if (options.closable == null) { options.closable = true; }
        if (options.modal == null) { options.modal = true; }
        if (options.onLoad == null) { options.onLoad = function () { } }
        if (options.onClose == null) { options.onClose = function () { } }
        options.iconCls = options.iconCls || "icon-old";
        options.buttons = options.buttons || [];
        if (options.handler) {
            options.buttons.push({
                text: "确定", iconCls: "icon-ok",
                handler: options.handler
            });
        }
        if (options.closable) {
            options.buttons.push({
                text: "关闭", iconCls: "icon-no",
                handler: function () {
                    manage.buttonCloseDialog(this);
                }
            });
        }
        return options;
    },
    //调整位置
    adjustmentDialog: function (dialog) {
        var boxwidth = $(dialog).parent().width();
        var boxheight = $(dialog).parent().height();
        if (boxheight > $(window).height() - 20) {
            dialog.dialog("resize", {
                height: $(window).height() - 20
            });
            manage.adjustmentDialog(dialog);
        }
        dialog.dialog("center");
    },
    //关闭窗口
    buttonCloseDialog: function (button) {
        $(".window-body", $(button).closest(".window")).dialog("close");
    },
    //工具栏初始化
    buttonInit: function (mtag, bind) {
        var links = $("a." + mtag + "func");
        for (var i = 0; i < links.length; i++) {
            var link = links.eq(i).removeClass(mtag + "func");
            var func = link.data("func"); link.removeData("func")
            link.removeData("func").bind("click", bind(func));
        }
    },
    //遮罩交互
    ajax: function (options) {
        $.ajax({
            type: options.type || "get",
            url: options.url,
            dataType: options.dataType || "json",
            data: options.data || {},
            success: options.success,
            beforeSend: function () {
                manage.showMask(options.obj);
            },
            complete: function () {
                manage.hideMask(options.obj);
            }
        });
    },
    //表单提交
    form: function (options) {
        $(options.formid).form("submit", {
            url: options.url,
            onSubmit: function () {
                var bool = $(this).form("validate");
                if (bool && options.onSubmit) {
                    bool = options.onSubmit();
                }
                if (bool) { manage.showMask(); }
                return bool;
            },
            success: function (result) {
                manage.hideMask();
                try {
                    result = JSON.parse(result);
                }
                catch (e) {
                    manage.msg("表单反馈解析失败");
                    console.info(result); return;
                }
                if (result.success) {
                    manage.slide(result.message);
                    options.success(result);
                    options.dialog.dialog("close");
                }
                else if (result.code == "LoginTimeout") {
                    manage.msg("登陆超时，请重新登陆", function () {
                        location.replace("/work/authorize/login");
                    });
                }
                else { manage.msg(result.message); }
            }
        });
    },
    //链接类型菜单
    menuHref: function (url) {
        $(".theme-container").panel("destroy");
        var containerBox = $("#theme-layout").layout("panel", "center");
        var container = $("<div />").addClass("theme-container").appendTo(containerBox);
        container.panel({ fit: true, border: false, href: url });
    },
    //网页类型菜单
    menuFrame: function (url) {
        $(".theme-container").panel("destroy");
        var containerBox = $("#theme-layout").layout("panel", "center");
        var container = $("<div />").addClass("theme-container").appendTo(containerBox);
        var iframe = "<iframe class='manage-iframe' src='" + url + "'></iframe>";
        container.panel({ fit: true, border: false, content: iframe, bodyCls: "theme-container-iframe" });
    },
    //弹窗类型菜单
    menuDialog: function (url) {
        if (url) {
            manage.ajax({
                url: url, dataType: "text",
                success: function (result) {
                    $("#layout-common-code").html(result);
                }
            });
        }
    },
    //修改密码
    updatePwd: function () {
        var d = manage.dialog({
            title: "修改密码", width: 420,
            href: "/basic/user/updatepwd",
            bodyCls: "theme-container",
            handler: function () {
                manage.form({
                    dialog: d, formid: "#updatepwd",
                    url: "/basic/user/setupdatepwd",
                    success: function (result) { }
                });
            },
            onLoad: function () { }
        });
        $(".theme-navigate-user-panel").menu("hide");
    },
    //注销登录
    logout: function () {
        manage.confirm("确认注销?", function (ec) {
            if (ec) {
                location.replace("/work/authorize/login");
            }
        });
        $(".theme-navigate-user-panel").menu("hide");
    },
    //菜单事件
    menuOnClick: function (node) {
        var type = $(node).data("type");
        var href = $(node).data("href");
        switch (type) {
            case "href":
                manage.menuHref(href); break;
            case "iframe":
                manage.menuFrame(href); break;
            case "dialog":
                manage.menuDialog(href); break;
            default: break;
        }
    },
    //编辑器
    initEditor: function (id, width, height) {
        width = width || 540;
        height = height || 500;

        UE.getEditor(id, {
            snapscreenHost: "127.0.0.1",
            imageCompressEnable: false,
            compressSide: 1,
            catchRemoteImageEnable: !0,
            catchFieldName: "imgurl",
            toolbars: [
                ["source", "|", "undo", "redo", "|", "fontfamily", "fontsize", "|", "blockquote", "horizontal", "removeformat", "formatmatch", "link", "unlink", "|", "insertvideo", "music", "insertimage", "drafts"],
                ["bold", "italic", "underline", "forecolor", "backcolor", "|", "justifyleft", "justifycenter", "justifyright", "|", "rowspacingtop", "rowspacingbottom", "lineheight", "|", "insertorderedlist", "insertunorderedlist", "|", "imagenone", "imageleft", "imageright", "imagecenter"]
            ],
            labelMap: { anchor: "", undo: "" },
            //默认的编辑区域宽度
            initialFrameWidth: width,
            //默认的编辑区域高度
            initialFrameHeight: height,
            //开启滚动条
            scaleEnabled: true,
            //关闭字数统计
            wordCount: false,
            //关闭elementPath
            elementPathEnabled: false
        });
    },
    //日期格式化
    dataFormat: function (date, fmt) { //author: meizz 
        var o = {
            "M+": date.getMonth() + 1, //月份 
            "d+": date.getDate(), //日 
            "h+": date.getHours(), //小时 
            "m+": date.getMinutes(), //分 
            "s+": date.getSeconds(), //秒 
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    },
    //通用导出
    exportGrid: function (target) {
        var t = $(target), opts = t.datagrid("options");
        if (opts.pagination) { //远程排序情况下全部导出
            var queryParams = $.extend({}, opts.queryParams);
            $.extend(queryParams, { page: 1, rows: 100000 }); //10万以上数据就不要逗比了                
            if (opts.sortName) { $.extend(queryParams, { sort: opts.sortName, order: opts.sortOrder }); }
            $.ajax({
                type: opts.method, url: opts.url, data: queryParams, dataType: "json",
                beforeSend: function () { t.datagrid("loading"); },
                complete: function () { t.datagrid("loaded"); },
                success: function (data) {
                    if (!$.isArray(data)) {
                        manage.exportExcel(target, data ? data.rows : []);
                    }
                    else { manage.exportExcel(target, data); }

                }, error: function () { }
            });
        }
        else {
            var data = $(target).data().datagrid.cache;
            if (!data) {
                var filter = $.data(target, 'datagrid').filterSource;
                if (filter) { data = filter; }
                else { data = t.datagrid("getRows"); }
            }
            if (!$.isArray(data)) {
                manage.exportExcel(target, data ? data.rows : []);
            }
            else { manage.exportExcel(target, data); }

        }
    },
    //导出表格
    exportExcel: function (target, rows) {
        var t = $(target), dgOptions = t.datagrid("options");
        if (rows.length == 0) { return; }

        var lastFrozenColumns = manage.exportGetColumns(target, true), lastColumns = manage.exportGetColumns(target, false);

        var maxGroup = lastFrozenColumns.length >= lastColumns.length ? lastFrozenColumns.length : lastColumns.length;
        var totalColumns = new Array(maxGroup);
        for (var k = 0; k < maxGroup; k++) {
            if (totalColumns[k] == undefined) { totalColumns[k] = []; }
            if (lastFrozenColumns.length != 0) {
                $.util.merge(totalColumns[k], lastFrozenColumns[k]);
            }
            if (lastColumns.length != 0) {
                $.util.merge(totalColumns[k], lastColumns[k]);
            }
        }
        //用formatter处理rows 为不影响datagrid本身的rows集合，先克隆rows
        var existFields = [], cloneRowsObj = $.extend(true, {}, rows), lastRows = [];
        for (var c in cloneRowsObj) {
            if ($.string.isNumeric(String(c))) { lastRows.push(cloneRowsObj[c]); }
        }

        function delHtmlTag(str) {
            if (str) { return str.replace(/<[^>]+>/g, ""); }//去掉所有的html标记
        }

        for (var index = 0; index < totalColumns.length; index++) {
            totalColumns[index].forEach(function (itemCol, itemColIndex) {
                if (itemCol.formatter && $.isFunction(itemCol.formatter)) {
                    lastRows.forEach(function (itemRow, itemRowIndex) {
                        var spe = true, rowIndex = !dgOptions.idField ? itemRowIndex : t.datagrid("getRowIndex", itemRow[dgOptions.idField]);
                        for (var prop in itemRow) {
                            if (prop == itemCol.field) {
                                var temp = itemRow[prop];
                                itemRow[prop] = itemCol.formatter.call(itemCol, itemRow[prop], itemRow, rowIndex);
                                if (!existFields.contains(itemCol.field)) {
                                    existFields.push(itemCol.field);
                                }
                                if (/<[^>]+>/g.test(itemRow[prop])) { itemRow[prop] = temp; }
                                spe = false; break;
                            }
                        }
                        if (spe) {
                            //处理特殊情况，遍历了row的属性，却没找到itemCol.field
                            // field 随便写，通过formatter强行显示指定数据
                            //将field的属性写入row中，其值为formatter的返回值
                            if (itemCol.field && !$.string.isNullOrWhiteSpace(itemCol.field)) {
                                //若该field已存在于 其他列的field 中，则不处理formatter，事实上，easyui也不会对这种formatter进行处理
                                if (!existFields.contains(itemCol.field)) {
                                    itemRow[itemCol.field] = delHtmlTag(itemCol.formatter.call(itemCol, itemRow[itemCol.field], itemRow, rowIndex));
                                }
                            }
                        }
                    });
                }
            });
        }

        //从lastRows的每个row中移除属性值类型为 array 或 object 的属性
        for (var k = 0; k < lastRows.length; k++) {
            var row = lastRows[k];
            for (var pro in row) {
                var tempValue = row[pro];
                if ($.isArray(tempValue) || $.util.isObject(tempValue)) { delete row[pro]; }
            }
        }

        //组装参数
        var param = { data: JSON.stringify(lastRows), columns: JSON.stringify(totalColumns) };

        //console.log("行数：");
        //console.log(rowspanCount);
        //console.log("********************");
        //console.log("列数：");
        //console.log(colspanCount);
        //console.log("********************");
        //console.log("最终列集合：");
        //console.log(totalColumns);
        //console.log("********************");
        //console.log("最终本页数据集合：");
        //console.log(rows);
        //console.log("********************");
        //console.log("参数：");
        //console.log(param);
        //console.log("********************");

        //模拟form提交完成导出excel操作
        $("iframe[name='hiddenIframe']").remove();
        $("form[target='hiddenIframe']").remove();

        //form的action指向，需结合后台配合，因此本扩展不是真正的easyui扩展。
        var tempForm = $('<form action="/other/common/export" target="hiddenIframe" method="post"></form>');
        for (var prop in param) {
            tempForm.append("<input name=\"" + prop + "\" type=\"hidden\" value='" + param[prop] + "' / >");
        }

        $("body").append("<iframe src=\"about:blank\" name=\"hiddenIframe\" style=\"display:none;\"></iframe>").append(tempForm);

        tempForm.submit();
    },
    //读取导出列
    exportGetColumns: function (target, frozen) {
        var t = $(target), dgOptions = t.datagrid("options");

        //取目标列集合
        var fColumns = frozen == true ? (dgOptions.frozenColumns || [[]]) : (dgOptions.columns || [[]]).clone();

        //过滤checkbox列和hidden列
        var ddddd = fColumns.clone();
        for (var k = 0; k < fColumns.length; k++) {
            var tempLen = fColumns[k].length;
            for (var inK = 0; inK < tempLen; inK++) {
                var needRemove = false, itemFc = fColumns[k][inK];

                //checkbox列
                //if (itemFc.checkbox && itemFc.checkbox == true) { needRemove = true; }
                //无title的列
                if (!itemFc.checkbox && $.string.isNullOrWhiteSpace(itemFc.title)) { needRemove = true; }
                //hidden列
                if (!needRemove && itemFc.hidden && itemFc.hidden == true) { needRemove = true; }

                if (needRemove) { fColumns[k].removeAt(inK); tempLen--; inK--; }
            }
        }

        //计算列集合的总列数总行数
        //总行数 = fColumns.length
        //总列数 = fColumns[item].colspan之和中最大的
        var colspanCount = $.array.max($.array.map(fColumns, function (itemFc) { return $.array.sum(itemFc, function (item) { return item.colspan || 1; }) })),
            rowspanCount = fColumns.length;

        var lastColumns = [];
        //组建最终列集合的数组结构
        for (var i = 0; i < rowspanCount; i++) {
            lastColumns[i] = new Array(colspanCount);
        }

        var getFixedColumnIndex = function (a) {
            for (var i = 0; i < a.length; i++) {
                if (a[i] == undefined) {
                    return i;
                }
            }
            return -1;
        };
        //往最终列集合里填充数据
        for (var columIndex = 0; columIndex < fColumns.length; columIndex++) {
            fColumns[columIndex].forEach(function (itemFc, itemIndex) {
                var fieldIndex = getFixedColumnIndex(lastColumns[columIndex]); //找到第一个未赋值的元素索引
                if (fieldIndex >= 0) {
                    for (var c = fieldIndex; c < colspanCount; c++) {
                        var tempCol = $.extend({}, itemFc, {});
                        if (tempCol.colspan == undefined) { tempCol.colspan = 1; }
                        if (tempCol.rowspan == undefined) { tempCol.rowspan = 1; }
                        if ((itemFc.colspan || 1) > 1) {
                            //若列是跨列的，则认为该列的field无效
                            delete tempCol.field;
                        }
                        lastColumns[columIndex][c] = tempCol;
                        if ((itemFc.rowspan || 1) > 1) {
                            for (var d = 1; d < itemFc.rowspan; d++) {
                                if (columIndex + d <= rowspanCount) {
                                    lastColumns[columIndex + d][c] = tempCol;
                                }
                            }
                        }
                        if ((itemFc.colspan || 1) > 1) {
                            for (var d = 1; d < itemFc.colspan; d++) {
                                if (c + d <= colspanCount) {
                                    lastColumns[columIndex][c + d] = tempCol;
                                }
                            }
                        }
                        break;
                    }
                }
            });
        }

        return lastColumns;
    },
    //载入完毕
    initLoaded: function () {
        setTimeout(function () {
            $(".theme-loading").fadeOut(500);
        }, 500);
    }
};

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function () { manage.initLoaded(); });